<template>
    <div class="InboundList-box">
       <!-- 资料列表 -->
        <h3 class="mb16">资料列表</h3>
        <!-- 搜索栏 -->
        <serchForm :Form="inventoryForm" :FormLabel="inventoryFormLabel" @onSearch="onSearch" />
        <!-- 增删改查 -->
        <div class="function-box" v-if="checkPermi(['system:inventory:edit'])">
                <el-button class="addBtn2" @click="add">新增</el-button>
                <el-button class="delBtn2" @click="dels">删除</el-button>
        </div>
        <!-- 活动信息列表页面 -->
    <forTableCom
      :color="color"
      :idActive="idActive"
      :bg="bg"
      :total="total"
      :page="pageNum"
      :limit="pageSize"
      @handleSelectionChange="handleSelectionChange"
      @handleChange="handleChange"
      @updatePage="updatePage"
      @updateLimit="updateLimit"
      :tableHeaderData="inventoryTableHeaderData"
      :tableData="inventoryTableData"
      :uploadShow='uploadShow'
      @uploadDel="uploadDel"
      @uploadDownload="uploadDownload"
      @uploadYulan="uploadYulan"
      :pagination="inventoryTableData.length>0"
    >
    </forTableCom>
    <!-- 添加或修改用户配置对话框 -->
      <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
         <el-form :model="form" :rules="rules" label-position="top" ref="userRef" label-width="80px">
            <div class="formItembox">
               <el-form-item class="formItem" label="资料名称" prop="name">
                     <el-input v-model="form.name" placeholder="请输入资料名称" maxlength="11" />
                  </el-form-item>
                  <el-form-item class="formItem" label="资料类型" prop="categoryCode">
                     <el-select v-model="form.categoryCode" placeholder="请选择资料类型">
                        <el-option
                           v-for="item in options"
                           :key="item.code"
                           :label="item.name"
                           :value="item.code"
                        ></el-option>
                     </el-select>
                  </el-form-item>
                             
                  <el-form-item class="formItem" label="备注">
                     <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                  </el-form-item>
            </div>
         </el-form>
         <!-- 上传图片 -->
          <p class="uploadTitle">上传文件</p>
          <FileUpload
                  v-model="form.fileUrl"
                  :fileType="['']"
                  :limit="1"
                  :fileSize="500"
                  :modelValue="form.fileUrl"
                  @update:modelValue="handlerModelValue"
                  @size="size"
                />
                <!-- <p>{{ form.fileUrl }}</p> -->
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="cancel">重置</el-button>
               <el-button type="primary" @click="submitForm">提交</el-button>
            </div>
         </template>
      </el-dialog>

      <!-- 预览 -->
    <el-dialog v-model="dialogVisible" title="预览"  @closed="pauseVideo" :key="nodekey">

      <!-- pdf线上地址预览 -->
      <vue-pdf-embed 
      v-if="wenjianType==='.pdf' "
      :source="pdfUrl" 
      style="border: 1px solid #ddd; margin-top: 20px"
    />
    
    <!-- xlsx线上地址预览 -->
    <div v-if="wenjianType==='.xlsx' || wenjianType==='.xls' ">
    <div>
      <table border class="excel-table">
        <thead>
          <tr>
            <th v-for="(header, index) in headers" :key="index">{{ header }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, rowIndex) in sheetData" :key="rowIndex">
            <td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    </div>
    <!-- 预览docx文件 -->
    <div v-if="wenjianType==='.docx' " ref="docxContainer" class="docx-preview"></div>
    <!-- 视频预览 -->
    <div v-if="wenjianType==='.mp4' || wenjianType==='.webm' || wenjianType==='.ogg' " class="video-wrapper">
        <video
          ref="videoPlayer"
          controls
          controlsList="nodownload"
          class="video-element"
        >
          <source :src="videoUrl" :type="videoType">
          您的浏览器不支持 HTML5 视频标签。
        </video>
    </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片线上地址预览 -->
    <div v-if="showPreview" class="preview-modal" @click.self="closePreview">
      <div class="preview-content">
        <img :src="currentImage" class="preview-image" />
        <button class="close-button" @click="closePreview">
          <svg viewBox="0 0 24 24" width="24" height="24">
            <path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
          </svg>
        </button>
      </div>
    </div>

    </div>
</template>

<script setup>
import { ref, reactive, toRefs,computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import serchForm from '@/components/inventory/serchForm.vue'
import { checkPermi } from '@/utils/permission.js'
import forTableCom from '@/components/forTableCom/index.vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import {listUser,delUser,addUser} from '@/api/system/upload.js'
import {quickCodeChildrenApi} from '@/api/system/dict/type.js'
import { getToken } from "@/utils/auth";
import FileUpload from '@/components/FileUpload'
import VuePdfEmbed from 'vue-pdf-embed';
import * as XLSX from 'xlsx';
import { renderAsync } from 'docx-preview';


const router = useRouter();
const route = useRoute();
const data = reactive({});
const { proxy } = getCurrentInstance();
let nodekey = ref(Math.random())

const title = ref("");
const open = ref(false);
const form = ref({
     fileUrl:'',      //文件地址
     fileType:'',       //类型
     name:'',   //资料名称
     remark:'',         //备注
     categoryCode:'',  //新增时候选择的类型
     fileSize:'',      //文件大小
  })
/** 重置操作表单 */
function reset() {
  form.value = {
    fileUrl: undefined, 
    name: undefined,
    remark: undefined,
    fileType:undefined,
    categoryCode:undefined,  //新增时候选择的类型
    fileSize:undefined,      //文件大小
  };
  proxy.resetForm("userRef");
};
const rules = ref({
    name: [{ required: true, message: "请输入资料名称", trigger: "blur" }],
    fileUrl: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
    categoryCode: [{ required: true, message: "请选择资料类型", trigger: "change"}],
  })

// 表单
let inventoryForm = ref({
  categoryCode:'',//资料类型
  uploadDate: '', // 上传时间
  name: '', // 资料名称
  id:'', // 资料编号
})
// 表单数据标题
let inventoryFormLabel = ref([
  {
    name: 'uploadDate',
    label: '上传时间',
    type: 'datetimerange',
  },
  {
    name: 'id',
    label: '资料编号',
  },
  {
    name: 'name',
    label: '资料名称',
  },
  {
    name: 'categoryCode',
    label: '资料类型',
    type:'select',
    client: [],
  },
])
// 查找
const onSearch = (v) => {
  console.log(v,'查看入库页面时间参数')
  // 每次查询后回到页1
  pageNum.value = 1
  v.startDate = v.uploadDate[0]
  v.endDate = v.uploadDate[1]
  listUserApiFn(v)
}

// 显示操作栏
const uploadShow = ref(true)
let idActive = 'id'
// 表格
let color = ref('#333')
let bg = ref('#d9d9d93b')
// 总条目数   pageSize 加 1
let total = ref(0)
// 当前页数
let pageNum = ref(1)
// 条数
let pageSize = ref(50)
// 存储勾选框的对象
let multipleSelection = ref([])
const piliangIds = ref('')
// 选中的列
let idList = []
const handleSelectionChange = (v) => {
  multipleSelection.value = v.map(item => item.id);
  idList = Array.from(multipleSelection.value)
  piliangIds.value = multipleSelection.value.join(',')   //批量删除用的
}
// 分页器大小  当前分页器
const handleChange = (v) => {
  let { page, limit } = v.page
  pageNum.value = page
  pageSize.value = limit
  let params = inventoryForm.value
  listUserApiFn(params)
}
// 当前页面位置发生变化
const updatePage = (v) => {
  console.log(v)
}
// 条目个数发生变化
const updateLimit = (v) => {
  console.log(v)
}
// 表格表头数据
let inventoryTableHeaderData = ref([
  {
    prop: 'id',
    label: '资料编号',
    sortable: true
  },
  {
    prop: 'name',
    label: '资料名称',
  },
  {
    prop: 'fileUrl',
    label: '资料地址',
  },
  {
    prop: 'nickName',
    label: '发布人',
  },
  {
    prop: 'categoryCode',
    label: '资料类型',
  },
  {
    prop: 'remark',
    label: '备注',
  },
  {
    prop: 'uploadDate',
    label: '上传时间',
    sortable: true
  },
])
// 表格数据内容
let inventoryTableData = ref([])
const uploadDel = (val)=>{  //列表单个删除操作
      let {i , v} = val
      console.log(v.id);
      
      ElMessageBox.confirm(
    '确定要删除该资料吗?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
         delUser(v.id).then(res=>{
              if(res.code===200){
                   ElMessage({
                 message: '删除成功',
                 type: 'success',
               })
               listUserApiFn()
              }
         })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

const uploadDownload = async (val) => { //下载按钮
    let { i, v } = val;
    console.log(v.fileUrl, '打印这个下载地址');

    try {
        // 获取文件名（如果未提供则从URL中提取）
        var index = v.fileUrl.lastIndexOf('.')
        var name = v.fileUrl.slice(index)

        var index2 = v.fileUrl.lastIndexOf('/')
        var index3 = v.fileUrl.lastIndexOf('_')
        var name2 = v.fileUrl.slice(index2 + 1, index3)

        let filename = name2 + '' + name || '';  //获取文件名
        // if (!filename) {
        //     const urlParts = v.fileUrl.split('/');
        //     filename = urlParts[urlParts.length - 1].split('?')[0];
        // }

        // 使用fetch API获取文件
        const response = await fetch(v.fileUrl, {
            mode: 'cors', // 尝试跨域请求
            headers: new Headers({
                'Origin': window.location.origin,
            }),
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        // 获取文件blob
        const blob = await response.blob();
        
        // 创建对象URL
        const blobUrl = window.URL.createObjectURL(blob);
        
        // 创建隐藏的下载链接
        const link = document.createElement('a');
        link.href = blobUrl;
        link.download = filename;
        link.style.display = 'none';
        document.body.appendChild(link);
        
        // 触发点击
        link.click();
        
        // 清理
        setTimeout(() => {
            document.body.removeChild(link);
            window.URL.revokeObjectURL(blobUrl);
        }, 100);
    } catch (error) {
        console.error('下载失败:', error);
        
        // 如果fetch方式失败，尝试直接使用原始URL（适用于同源或服务器允许直接下载的情况）
        const link = document.createElement('a');
        link.href = v.fileUrl;
        link.download = filename || 'download';
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}

const add = ()=>{ //打开新增弹出框
    reset()
    open.value = true
    title.value = '新增资料'
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
       addUser(form.value).then(res=>{
           if(res.code===200){
              ElMessage({
                 message: '添加成功',
                 type: 'success',
               })
               open.value = false
               listUserApiFn()
           }
           
       })
    }
  });
};
const dels = ()=>{   //批量删除
    if(idList.length===0){
       ElMessage({
                 message: '请先选择要拒绝的数据',
                 type: 'error',
               })
      return false
  }
     ElMessageBox.confirm(
    '确定要删除该资料吗?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
         delUser(piliangIds.value).then(res=>{
              if(res.code===200){
                   ElMessage({
                 message: '删除成功',
                 type: 'success',
               })
               listUserApiFn()
              }
         })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}
const cancel = ()=>{  //重置
    reset()
}
// 查询资料列表数据
const listUserApiFn = async (data='') => {
  let page = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  }
  let params = JSON.parse(JSON.stringify(Object.assign(page,data)))
  // let params = Object.assign(data, page)  //这种写法会导致日期无法搜索
  delete params.uploadDate
  console.log(params,'打印这个params');
  
  let res = await listUser(params)
  let { code, rows } = res
  if (code == 200) {
    console.log(rows,'打印资料列表数据');
    // total.value = res.total
    inventoryTableData.value = rows
    total.value = res.total
  }
}
let options = ref([])
const quickCodeChildrenApiFn =()=>{  //通过快码获得资料类型
    quickCodeChildrenApi({parentCode:30000}).then(res=>{
        console.log(res,'查询子集快码');
        if(res.code===200){
           options.value = res.rows
           res.rows.forEach((v) => {
           inventoryFormLabel.value[3].client.push({
             label: v.name,
             value: v.code,
           })
         })
        }
    })
}

// 图片上传
// 获取的图片
const handlerModelValue = (v) => {
  // form.value.fileUrl = v.replace('://erp.urldng.com:33000/', '://erp.urldng.com:33000/prod-api/');
  if(v){
      form.value.fileUrl = v
      var index = v.lastIndexOf('.'); //用于返回指定字符串在当前字符串中最后一次出现的位置。
      var name = v.slice(index); //目的用来截取.jpg等字段
      form.value.fileType = name.replace(".", "");
      console.log(v,'上传的图片地址');
  }
}
const size = (val)=>{
     console.log(val,'文件大小');
     form.value.fileSize = val
}

//预览功能
const dialogVisible = ref(false)
const wenjianType = ref('')
const sheetData = ref([]);
const headers = ref([]);
const pdfUrl = ref(''); 
const showPreview = ref(false);
const currentImage = ref('');

const docxContainer = ref(null);

const videoPlayer = ref(null);
const videoUrl = ref('')
const videoUrlType = ref('')
const videoType = computed(() => {  //播放视频
  const ext = videoUrlType.value.split('.').pop().toLowerCase();
  switch(ext) {
    case 'mp4': return 'video/mp4';
    case 'webm': return 'video/webm';
    case 'ogg': return 'video/ogg';
    default: return 'video/mp4';
  }
});
const pauseVideo = () => { //关闭视频
  if (videoPlayer.value) {
    videoPlayer.value.pause();
    videoPlayer.value.currentTime = 0;
  }
};

const uploadYulan = async(val)=>{ //查看按钮
    let {i , v} = val
    videoUrlType.value = v.fileUrl
    var index = v.fileUrl.lastIndexOf('.') //用于返回指定字符串在当前字符串中最后一次出现的位置
    var newname = v.fileUrl.slice(index); //目的用来截取.jpg等字段
    wenjianType.value = newname

    if(['.xlsx', '.xls'].includes(newname)){   //预览线上xlsx文件
      dialogVisible.value = true
         // 获取文件
    const response = await fetch(v.fileUrl);
    const arrayBuffer = await response.arrayBuffer();
    
    // 解析Excel
    const workbook = XLSX.read(arrayBuffer);
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    
    // 转换为JSON
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
    
    if (jsonData.length > 0) {
      headers.value = jsonData[0];
      sheetData.value = jsonData.slice(1);
    }
    }else if(newname==='.pdf'){  //预览线上pdf文件
        dialogVisible.value = true
        pdfUrl.value = v.fileUrl
    }else if(['.png', '.jpg', '.jpeg'].includes(newname)){  //预览图片
         currentImage.value = v.fileUrl;
         showPreview.value = true;
         document.body.style.overflow = 'hidden'; // 防止背景滚动
    }else if(newname==='.docx'){
             try {
           dialogVisible.value = true
           // 获取文件内容
           const response = await fetch(v.fileUrl);
           const arrayBuffer = await response.arrayBuffer();
           // 渲染 DOCX
           await renderAsync(arrayBuffer, docxContainer.value);
         } catch (error) {
           console.error('预览失败:', error);
           ElMessage.error('文档预览失败');
         }
    }else if(newname==='.mp4'){
          dialogVisible.value = true
          nodekey.value = Math.random()
          videoUrl.value = v.fileUrl
          setTimeout(() => {
          if (videoPlayer.value) {
            videoPlayer.value.play().catch(e => console.error('自动播放失败:', e));
          }
        }, 300);
    }else{
       ElMessage({
                 message: '暂不支持预览',
                 type: 'error',
               })
    }
}
// 关闭查看
const closePreview = () => {
  showPreview.value = false;
  document.body.style.overflow = '';
};
// 点击ESC键关闭查看
const handleKeyDown = (e) => {
  if (e.key === 'Escape' && showPreview.value) {
    closePreview();
  }
};
// 添加键盘事件监听
window.addEventListener('keydown', handleKeyDown);

onMounted(()=>{
    Promise.all([listUserApiFn(),quickCodeChildrenApiFn()])
})

</script>

<style lang='scss' scoped>
.InboundList-box {
    padding: 16px;
    .function-box {
    display: flex;
    align-items: center;
  }
}
.dialog-footer {
  display: flex;
  justify-content: center; /* 水平居中 */
}
.formItembox {
      display: flex;
      flex-wrap: wrap;
      // justify-content: space-between;
      box-sizing: border-box;

      .formItem {
        width: 28%;
        // display: flex;
        margin-right: 70px;
      }
      .formItem:last-child {
        width: 100%;
        margin-right:0;
      }
      .formItem:nth-child(3) {
        margin-right:0;
      }
    }
:deep(.el-select .el-input__wrapper) {
  width: 269px;
}
:deep(.el-textarea__inner){
    height: 80px;
}


.excel-table{
   border: 1px solid rgb(0, 0, 0);
        border-image: none;
        width: 100%;
        text-align: center;
        border-collapse: collapse;
        background-color: rgb(255, 255, 255);
}
:deep(.el-form-item:nth-child(4) .el-form-item__label) {
  margin-left: 0;
}

//图片预览样式
.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.preview-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
}

.preview-image {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
  border-radius: 4px;
}

.close-button {
  position: absolute;
  top: -40px;
  right: -40px;
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 24px;
  padding: 10px;
  transition: transform 0.2s;
}

.close-button:hover {
  transform: scale(1.2);
}

@media (max-width: 768px) {
  .close-button {
    top: -50px;
    right: 10px;
  }
}
//docx预览
.docx-preview {
  overflow: auto;
  border: 1px solid #eee;
}
:deep(.docx-wrapper) {
  padding: 0;
  background: #fff;
}

//视频预览
.video-wrapper {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 比例 */
  height: 0;
  overflow: hidden;
}

.video-element {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .video-thumbnail {
    max-width: 100%;
  }
}

.uploadTitle{
  margin-bottom: 8px;
  font-weight: 600;
}
</style>
